<template>
    <div>
        <span @click="handleVisible(true)">
            <!-- 自定义选择商品按钮 -->
            <slot name="btn">
                <el-button type="primary"> {{ selectedRow?.id ? '重新' : '' }}选择商品 </el-button>
            </slot>
        </span>
        <el-dialog
            class="good_template_dialog"
            title="选择商品"
            v-model="visible"
            width="80%"
            @close="handleVisible(false)">
            <div class="good_template_dialog_header">
                <el-form ref="formRef" :model="form" label-width="auto" @submit.prevent>
                    <el-row justify="space-between">
                        <el-col :span="8">
                            <el-form-item label="商品名称" prop="title">
                                <el-input v-model="form.goodsName" clearable placeholder="商品名称/商品编码"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8" style="padding-left: 24px; text-align: right">
                            <!-- <el-button @click="resetHandler">清空</el-button> -->
                            <el-button type="primary" @click="searchHandler">查询</el-button>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
            <el-table
                :data="tableList"
                @selection-change="handleSelectionChange"
                style="margin-top: 20px"
                height="350"
                ref="multipleTableRef">
                <el-table-column v-if="isMulti" type="selection" width="55" />
                <el-table-column v-for="{ prop, ...rest } in tableColumns" :key="prop" :prop="prop" v-bind="rest">
                    <template #default="{ row }">
                        <div class="custom-goods-name" v-if="prop === 'goodsName'">
                            <el-image
                                style="width: 40px; height: 40px"
                                :src="row?.materialSrc?.[0]?.materialSrc"
                                fit="fill"></el-image>
                            <span>{{ row.goodsName }}</span>
                        </div>
                        <el-button
                            v-if="prop === 'operation'"
                            size="small"
                            @click="handleSelect(row)"
                            :disabled="selectedRow?.id === row.id">
                            {{ selectedRow?.id === row.id ? '已选择' : '选择' }}</el-button
                        >
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <div style="margin-top: 15px">
                <Pagination
                    :total="totalCount"
                    :page-size="form.pageSize"
                    :current-page="form.pageNum"
                    @sizeChange="changeSizeHandler"
                    @pageChange="changePageHandler" />
            </div>
            <template #footer v-if="isMulti">
                <div style="flex: auto">
                    <el-button plain @click="handleVisible(false)">取消</el-button>
                    <el-button type="primary" @click="handleConfirm">确认</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { cloneDeep } from '@/commons/utils';
import { ElMessage } from 'element-plus';
import request from '@/request';
import Pagination from '@/components/Pagination.vue';
import { getShopListHook } from '@/hooks';

/* ---------------------------------- 父级通信 start ---------------------------------- */
const emit = defineEmits(['handle-confirm']);
const props = defineProps({
    isMulti: {
        type: Boolean,
        default: true
    },
    selectClose: {
        type: Boolean,
        default: true
    }
});
/* ---------------------------------- 父级通信 end ---------------------------------- */

/* ---------------------------------- 查询表格 start ---------------------------------- */
const form = reactive({
    pageNum: 1,
    pageSize: 10,
    shopId: 0,
    goodsName: ''
});
const formClone = cloneDeep(form); // 查询表单备份
const formRef = ref();
let shopList = reactive([]); // 店铺下拉列表

const totalCount = ref(0);
let tableList = reactive([]);
const tableColumns = reactive([
    { label: '商品信息', prop: 'goodsName', minWidth: '250' },
    { label: '销售价', prop: 'price' },
    { label: '库存', prop: 'shopInfoText', width: '100' },
    { label: '已参与活动', prop: 'activityNameText', width: '100' }
]);
/* ---------------------------------- 查询表格 end ---------------------------------- */

let selectedRow = reactive({}); // 已选中的商品
const multipleTableRef = ref();
let goodIds = reactive([]); // 多选的商品ids

/* ---------------------------------- 控制弹窗 start ---------------------------------- */
let visible = ref(false);
// 展示隐藏
const handleVisible = (isVisible = false) => {
    if (!isVisible) {
        multipleTableRef.value?.clearSelection();
        formRef.value.resetFields();
        Object.assign(form, cloneDeep(formClone));
        searchHandler();
    }
    visible.value = isVisible;
};
/* ---------------------------------- 控制弹窗 end ---------------------------------- */

const handleSelect = row => {
    if (props.selectClose) {
        // const keys = Object.keys(selectedRow);
        // let obj = {};
        // keys.forEach(item => {
        //     obj[item] = null;
        // });
        // Object.assign(selectedRow, row);
        handleVisible(false);
    } else {
        // Object.assign(selectedRow, row);
    }
    Object.assign(selectedRow, row);
    emit('handle-confirm', row);
};

const handleSelectionChange = val => {
    goodIds.length = 0;
    Object.assign(
        goodIds,
        val?.map(item => item.id)
    );
};

// 确认按钮
const handleConfirm = async () => {
    if (goodIds.length < 1) {
        ElMessage({
            type: 'error',
            message: '请先选择商品'
        });
        return;
    }
    emit('handle-confirm', goodIds);
    handleVisible(false);
};

/**
 * 重置
 */
const resetHandler = () => {
    formRef.value.resetFields();
    Object.assign(form, formClone);
    searchHandler();
};

/**
 * 搜索
 */
const searchHandler = () => {
    form.pageNum = 1;
    queryCouponListHandler();
};
/**
 * 分页
 * @param {*} page
 */
const changePageHandler = page => {
    form.pageNum = page;
    queryCouponListHandler();
};

/**
 * 每页记录数修改
 * @param {*} perPage
 */
const changeSizeHandler = perPage => {
    form.pageNum = 1;
    form.pageSize = perPage;
    queryCouponListHandler();
};
/**
 * 分页查询
 */
const queryCouponListHandler = async () => {
    const { data } = await request('choiceGoodsList', form);
    tableList.length = 0;
    Object.assign(
        tableList,
        data.list.map(item => {
            if (item.goodsMinPrice === item.goodsMaxPrice) {
                item.price = `￥${item.goodsMinPrice / 100}`;
            } else {
                item.price = `￥${item.goodsMinPrice / 100}~${item.goodsMaxPrice / 100}`;
            }
            item.shopInfoText = item?.shopInfo?.[0]?.shopName;
            item.activityNameText = item?.partakeActivity?.length ? item?.partakeActivity?.join() : '-';
            return item;
        })
    );
    totalCount.value = data.totalCount;
};

// 获取店铺
const getshopList = async () => {
    const { data } = await getShopListHook();
    shopList.length = 0;
    const list = data?.list || [];
    list.unshift({ shopName: '全部店铺', shopId: 0 });
    Object.assign(shopList, list);
};

onMounted(() => {
    getshopList();
    searchHandler();
});
</script>

<style lang="scss">
.good_template_dialog {
    max-width: 1000px;
    min-width: 900px;
}
</style>
<style lang="scss" scoped>
.good_template_dialog {
    &_header {
        width: 100%;
        .el-form > div {
            flex-wrap: nowrap;
        }
    }
    .center-operation {
        padding: 20px 0;
        display: flex;
        border-bottom: 1px solid #eaeaea;
        justify-content: space-between;
    }
    .custom-goods-name {
        display: inline-flex;
        align-items: center;
        span {
            margin-left: 4px;
        }
    }
}
</style>
